from PySide6.QtCore import Qt, Signal, Slot
from PySide6.QtWidgets import QLabel, QPushButton, QVBoxLayout, QWidget

from adddialogwidget import AddDialogWidget

'''
新建功能-新建发起窗口（作为 QTabWidget 的一个 Tab ）-调用 AddDialogWidget
'''


class NewAddressTab(QWidget):
    """ An extra tab that prompts the user to add new contacts.
        To be displayed only when there are no contacts in the model.
    """

    send_details = Signal(bool, str, str)  # 定义signal（关闭 新增dialog窗口 时触发），怎加了bool参数，确保从菜单调用时正确性，原demo的代码似乎不够严谨

    def __init__(self, parent=None):
        super().__init__(parent)

        description_label = QLabel("There are no contacts in your address book.\n Click Add to add new contacts.")
        add_button = QPushButton("Add")

        layout = QVBoxLayout()
        layout.addWidget(description_label)

        # 注意布局效果
        # https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/QBoxLayout.html#PySide6.QtWidgets.QBoxLayout.addWidget

        # addWidget -> (stretch) -> sizePolicy（If the stretch factor is 0 and nothing else in the QBoxLayout has a stretch factor greater than zero, the space is distributed according to the QWidget :sizePolicy() of each widget that’s involved.）
        # https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/QWidget.html#PySide6.QtWidgets.QWidget.sizePolicy 类似于Button的组件，默认行为是水平延申，垂直固定

        # https://doc.qt.io/qtforpython-6/PySide6/QtCore/Qt.html#PySide6.QtCore.Qt.AlignmentFlag
        # addWidget -> (alignment) -> The default alignment is 0, which means that the widget fills the entire cell.

        layout.addWidget(add_button, 0, Qt.AlignmentFlag.AlignCenter)
        # layout.addWidget(add_button,0)
        # layout.addWidget(add_button)

        self.setLayout(layout)
        add_button.clicked.connect(self.add_entry)

    @Slot()
    def add_entry(self):
        add_dialog = AddDialogWidget()
        # https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/QDialog.html#PySide6.QtWidgets.QDialog.exec
        if add_dialog.exec():
            name = add_dialog.name
            address = add_dialog.address
            self.send_details.emit(False,name, address)  # emit signal（传递参数）


if __name__ == "__main__":
    def print_address(name, address):
        print(f"Name: {name}")
        print(f"Address: {address}")


    import sys
    from PySide6.QtWidgets import QApplication

    app = QApplication(sys.argv)
    new_address_tab = NewAddressTab()
    new_address_tab.setWindowTitle("New Address Widget")
    new_address_tab.send_details.connect(print_address)  # connect signal
    new_address_tab.show()
    sys.exit(app.exec())
